<?php


namespace App\Admin\Forms\Config;


use App\Models\Config\SystemConfig;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

abstract class ConfigForm extends Form implements LazyRenderable
{
    use LazyWidget;

    abstract public static function label() :array;

    abstract public static function mapping() :array;

    abstract public function form();

    /**
     * 处理表单的提交
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        $labels = static::label();
        $fields = static::mapping();
        foreach ($fields as $key => $value){
            SystemConfig::updateOrCreate(["key"=>$value],["name" => Arr::get($labels,$key), "value" => Arr::get($input,$key)]);
        }
        $config = SystemConfig::pluck("value",'key')->toArray();
        Redis::connection('cache')->set(SystemConfig::class,json_encode($config));
        return $this->response()->success('设置成功');
    }

    /**
     * 表单默认值
     * @return mixed
     */
    public function default()
    {
        $keys = static::mapping();
        $all = SystemConfig::whereIn("key",array_values($keys))->pluck("value","key");
        $values = [];
        foreach ($keys as $k => $v){
            $values[$k] = Arr::get($all,$k) ?? config($v);
        }
        return $values;
    }


    public function savedScript()
    {
        return <<<'JS'
    if (data.status) {
        setTimeout(function () {
          location.reload()
        }, 1200);
    }
JS;
    }
}
